<template>
    <div>
        <a-tabs @change="tabChange" type="card" :active-key="showRange">
            <a-tab-pane tab="全部" key="1"></a-tab-pane>
            <a-tab-pane tab="小组" key="2"></a-tab-pane>
            <a-tab-pane tab="私人" key="3"></a-tab-pane>
        </a-tabs>
        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row :gutter="16">
                    <a-col :xl="6" :lg="7" :md="8" :sm="24">
                        <a-form-item label="分组">
                            <a-select v-model="searchParam.groupName" show-search placeholder="选择分组">
                                <a-select-option v-for="groupItem in groupList" :value="groupItem.groupName">
                                    {{
                                    groupItem.groupName
                                    }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :xl="5" :lg="5" :md="6" :sm="24">
                        <a-form-item label="文件类型">
                            <a-select v-model="searchParam.mediaType" placeholder="文件类型" style="width: 140px;"
                                      allowClear>
                                <a-select-option value="0">图片</a-select-option>
                                <a-select-option value="1">视频</a-select-option>
                                <a-select-option value="2">音频</a-select-option>
                                <a-select-option value="3">文件</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :xl="7" :lg="7" :md="8" :sm="24">
                        <a-form-item label="关键字">
                            <a-input v-model="searchParam.searchKeyword" placeholder="搜索文件(文件名/标签名)"
                                     style="width: 240px;" allowClear
                                     @pressEnter="searchFile">
                                <a-icon slot="prefix" type="search"/>
                            </a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :xl="7" :lg="7" :md="8" :sm="24">
                        <a-form-item label="上传时间">
                            <a-range-picker format="YYYY-MM-DD" v-model="searchTimes" :placeholder="['开始时间', '结束时间']"
                                            @change="onDateChange"/>
                        </a-form-item>
                    </a-col>
                    <a-col :xl="7" :lg="7" :md="8" :sm="24">
                        <a-form-item label="上传用户">
                            <j-select-multi-user :multi="false" v-model="searchParam.createBy"></j-select-multi-user>
                        </a-form-item>
                    </a-col>
                    <a-col :xl="7" :lg="7" :md="8" :sm="24">
                        <a-form-item label="作者">
                            <a-select v-model="searchParam.authorId" @focus="lazyLoadAuthor">
                                <a-select-option v-for="item in authorList" :key="item.id" :value="item.id">
                                    {{item.name}}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :xl="7" :lg="7" :md="8" :sm="24">
                        <a-form-item label="文件分类">
                            <a-tree-select
                                    v-model="searchParam.parentId"
                                    :tree-data="treeData"
                                    :replaceFields="{children:'crdFileBliList',key:'id',title:'fileName',value:'id'}"
                                    allow-clear></a-tree-select>
                        </a-form-item>
                    </a-col>
                    <a-col :xl="7" :lg="7" :md="8" :sm="24">
                        <a-form-item label="作品时间">
                            <j-date v-model="searchParam.contentTime"></j-date>
                        </a-form-item>
                    </a-col>
                    <a-col :xl="5" :lg="7" :md="8" :sm="24">
                        <a-form-item>
                            <a-button type="primary" @click="searchFile" icon="search">查询</a-button>
                            <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置
                            </a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator" :md="24" :sm="24">
            <a-button @click="handleAdd" type="primary" icon="plus" v-has="'file:upload'">新建</a-button>
            <a-button @click="handleFileClassify" type="primary" icon="unordered-list" v-has="'file:classify'">文件分类管理
            </a-button>
            <a-button @click="handleTag" type="primary" icon="tags" v-has="'file:tag'">标签管理</a-button>
        </div>
        <div>
            <a-row type="flex" :gutter="10">
                <a-col :span="18" :push="6">
                    <a-card>
                        <a-spin :spinning="loading">
                            <div>
                                <template v-for="(item, index) in path">
                                    <a-button type="link" v-if="index === path.length - 1" class="last">{{ item.pathName
                                        }}
                                    </a-button>
                                    <template v-else>
                                        <a-button type="link" @click="backFilePath(index)">{{ item.pathName }}
                                        </a-button>
                                        <span>&gt;</span>
                                    </template>
                                </template>
                            </div>
                            <a-empty v-if="!loading && dataSource.length == 0"></a-empty>
                            <a-row type="flex">
                                <a-col class="item" @click="goFilePath(item)" v-for="item in dataSource" :key="item.id">
                                    <div class="item-top">
                                        <a @click.stop="edit(item)">
                                            <a-icon type="edit"/>
                                        </a>
                                        <a-popconfirm title="确定删除吗?" @confirm.stop="handleDelete(item)"
                                                      v-has="'file:delete'">
                                            <a @click.stop>
                                                <a-icon type="delete"/>
                                            </a>
                                        </a-popconfirm>
                                        <template v-if="item.fileType == 1">
                                            <a v-has="'file:download'" @click.stop="downloadFolder(item.id)">
                                                <a-icon type="download"/>
                                            </a>
                                        </template>
                                        <template v-if="item.fileType > 1">
                                            <a-icon @click.stop="handleShare(item)" type="share-alt"
                                                    v-has="'file:download'"/>
                                            <a :href="item.fileUrl" :download="item.fileName" v-if="item.fileType == 2"
                                               v-has="'file:download'">
                                                <a-icon type="download"/>
                                            </a>
                                            <a :href="'http://' + item.fileUrl" download v-else v-has="'file:download'">
                                                <a-icon type="download"/>
                                            </a>
                                        </template>
                                    </div>
                                    <div class="img-box">
                                        <img v-if="item.fileType == 1" src="@/assets/file_type/directory.png"/>
                                        <img v-else-if="isImg(item)" @click.stop="showDetail(item)" :src="item.fileUrl"/>
                                        <img v-else-if="item.fileType == 2 && item.fileSuffix && fileTypeIcon[item.fileSuffix]"
                                             :src="fileTypeIcon[item.fileSuffix]"
                                             @click="preview(item)"
                                             />
                                        <template v-else-if="item.fileType == 3">
                                            <img :src="'http://' + item.imageUrl" @click="showDetail(item)" v-if="item.bigFileStatus >= 4"/>
                                            <div class="video-encode" v-else>视频转码中</div>
                                        </template>
                                        <img v-else src="@/assets/file_type/other.png" @click="preview(item)"/>
                                    </div>
                                    <div class="item-name text-ellipsis">{{ item.fileName }}</div>
                                    <div class="item-time text-ellipsis">{{ item.updateTime || item.createTime }}</div>
                                    <file-tags :tag="item.tag"></file-tags>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col class="file-num">共{{dirNum}}个文件夹，{{fileNum}}个文件</a-col>
                            </a-row>
                        </a-spin>
                    </a-card>
                </a-col>
                <a-col :span="6" :pull="18">
                    <a-card style="height: 100%;">
                        <a-directory-tree :defaultExpandAll="true"
                                          :replaceFields="{children:'crdFileBliList',key:'id',title:'fileName'}"
                                          :selectedKeys.sync='selectedKeys'
                                          @select="onSelect"
                                          :treeData="treeData">
                            <a-icon slot="icon" type="folder-open"/>
                        </a-directory-tree>
                    </a-card>
                </a-col>
            </a-row>
        </div>

        <add-modal ref="addModal" @refresh="queryFiles"></add-modal>
        <share-modal ref="shareModal"></share-modal>
        <image-view-modal ref="imageViewModal"></image-view-modal>
        <movie-modal ref="movieModal"></movie-modal>
        <movie-modal-small ref="movieModalSmall"></movie-modal-small>

        <file-classify-modal ref="fileClassifyModal" @refresh="queryFileClassify"></file-classify-modal>
        <tag-modal ref="tagModal"></tag-modal>
         <j-modal title="视频预览" width="800px" :visible.sync="previeVis" okText="确定"  @ok="closePreview" @cancel="closePreview">
             <video width="725px" ref="videoPlayer" controls="controls" :src=previewUrl />
        </j-modal>
    </div>
</template>

<script>
    //内容库列表
    import ShareModal from './modules/ShareModal'
    import ImageViewModal from './modules/ImageViewModal'
    import MovieModal from './modules/MovieModal'
    import MovieModalSmall from './modules/MovieModalSmall'

    import {getAction} from '@/api/manage'
    import AddModal from './modules/AddModal'
    import {isImg} from '@/utils/xinkeUtil'
    import FileTags from '../../components/xinke/FileTags'
    import FileClassifyModal from "./modules/FileClassifyModal";
    import TagModal from "./modules/TagModal";
    import {postAction} from "../../api/manage";

    const moment = require('moment')

    export default {
        name: 'DiskList',
        components: {TagModal, FileClassifyModal, FileTags, AddModal, ShareModal, ImageViewModal, MovieModal,MovieModalSmall},
        data() {
            this.fileTypeIcon = {
                dir: require('@assets/file_type/directory.png'),
                jpg: require('@assets/file_type/jpg.png'),
                png: require('@assets/file_type/jpg.png'),
                mp3: require('@assets/file_type/mp3.png'),
                mp4: require('@assets/file_type/mp4.png'),
                pdf: require('@assets/file_type/pdf.png'),
                txt: require('@assets/file_type/txt.png'),
                doc: require('@assets/file_type/word.png'),
                xls: require('@assets/file_type/xls.png'),
                zip: require('@assets/file_type/zip.png'),
                rar: require('@assets/file_type/zip.png')
            };

            this.url = {
                list: 'filebank/api/queryFileBankList'
            };
            this.fileClassifyId = null;
            this.parentId = null;
            return {
                loading: false,
                searchParam: {},
                searchTimes: null,
                showRange: '1',
                dataSource: [],
                path: [],
                groupList: [],
                dirNum: '',
                fileNum: '',
                authorList: [],
                treeData: [],
                selectedKeys:[],
                previeVis:false,
                previewUrl:''
            }
        },
        watch: {
            dataSource(newVal, oldVal) {
                let dirNum = 0, fileNum = 0;
                if (newVal) {
                    newVal.forEach(item => {
                        item.fileType == 1 ? dirNum++ : fileNum++;
                    });
                }
                this.dirNum = dirNum;
                this.fileNum = fileNum;
            }
        },
        created() {
            // this.loadData();
            this.loadAllGroup();
            this.queryFileClassify();
        },
        methods: {
            //查询作者列表
            async lazyLoadAuthor() {
                if (this.authorList.length === 0) {
                    const authorList = await getAction('crdcontent/crdAuthor/list',{pageSize:1000});
                    this.authorList = authorList.result.records;
                }
            },
            //查询文件分类
            async queryFileClassify() {
                const params = {fileGroupType: 0};
                const res = await getAction('filebank/api/queryFileGroupAndFolder', params);
                if (res && res.success) {
                    this.treeData  = res.result;
                }
            },
            //查询分类下的文件夹和文件
            async queryFiles(parentId,deletedPaths){
                parentId = parentId || this.parentId || this.fileClassifyId;
                const params = {fileType:0,fileGroupType: 1,parentId};
                try {
                    const res = await getAction('filebank/api/queryFileGroupAndFolder', params);
                    if (res && res.success) {
                        this.parentId = parentId;
                        this.dataSource = res.result;
                        return;
                    }
                    throw new Error();
                }catch (e) {
                    if(deletedPaths){
                        this.path.concat(deletedPaths);
                    }else{
                        this.path && this.path.pop();
                    }
                }
            },
            isImg(item) {
                return isImg(item)
            },
            tabChange(key) {
                this.showRange = key
                this.resetParams()
                this.queryFiles();
            },
            resetParams() {
                this.path = [];
                this.parentId = null;
            },
            //点击导航
            goFilePath(item) {
                if (item.fileType != 1) {
                    return
                }
                this.path.push({
                    pathName: item.fileName,
                    id: item.id
                });
                this.queryFiles(item.id);
            },
            backFilePath(index) {
                const deletePaths = this.path.splice(index + 1);
                this.queryFiles(this.path[this.path.length - 1].id,deletePaths);
            },
            searchFile() {
                this.selectedKeys = [];
                this.loading = true
                this.searchParam.showRange = this.showRange
                getAction('filebank/api/searchByKeyword', this.searchParam)
                    .then(res => {
                        if (res.success) {
                            // this.path = [{pathName: `搜索：${this.searchKeyword}`}]
                            this.path = []
                            this.dataSource = res.result
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                    .finally(() => {
                        this.loading = false
                    })
            },
            //新建
            handleAdd() {
                this.$refs.addModal.show('add',{showRange:this.showRange});
            },
            //编辑
            edit(item){
                this.$refs.addModal.show('edit',item);
            },
            //删除
            handleDelete(item) {
                getAction('filebank/api/delete', {id: item.id}).then(res => {
                    if (res.success) {
                        this.$message.success('删除成功')
                        this.queryFiles();
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            //分享
            handleShare(item) {
                this.$refs.shareModal.show(item)
            },
            async loadAllGroup() {
                const groupResult = await getAction('filebank/api/queryAllGroup')
                this.groupList = groupResult.result
            },
            searchReset() {
                this.searchParam = {}
                this.searchTimes = null
                this.queryFiles();
            },
            //分类选中
            onSelect(key, e) {
                if(e.selected){
                    this.resetParams();
                    this.path = [{
                        pathName: e.selectedNodes[0].dataRef.fileName,
                        id: e.selectedNodes[0].dataRef.id
                    }];
                    this.fileClassifyId = e.selectedNodes[0].dataRef.id;
                    this.queryFiles();
                }
            },
            showDetail(item) {
                console.log(item)
                switch (item.fileSuffix.toLowerCase()) {
                    case 'jpeg':
                    case 'jpg':
                    case 'gif':
                    case 'png':
                        this.showImageView(item)
                        break
                    case 'mp4':
                        this.getM3u8(item)
                        break
                    default:
                        return
                }
            },
            showImageView(item) {
                this.$refs.imageViewModal.show(item)
            },
            getM3u8(item) {
                getAction('filebank/api//getBigFIleById', {id: item.id}).then(res => {
                    if (res.success) {
                        console.log(res.result)
                        this.showMovieModal(res.result)
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            showMovieModal(item) {
                this.$refs.movieModal.show(item)
            },
            showMovieModal2(item) {
                this.previeVis=true
                this.previewUrl = item.fileUrl

            },
            closePreview(){
                this.previeVis = false
                this.previewUrl=""
            },
            onDateChange(e) {
                this.searchParam.startTime = moment(e[0]).format('YYYY-MM-DD 00:00:00')
                this.searchParam.endTime = moment(e[1]).format('YYYY-MM-DD 23:59:59')
            },
            //文件分类管理
            handleFileClassify() {
                this.$refs.fileClassifyModal.show();
            },
            //标签管理
            handleTag() {
                this.$refs.tagModal.show();
            },
            //下载文件夹：请求文件夹下的所有文件列表进行下载
            async downloadFolder(id) {
                const res = await postAction('filebank/api/downloadFolder', {id});
                if (res.success) {
                    const list = res.result;
                    if (list.length === 0) {
                        this.$message.warn('该文件夹为空');
                        return;
                    }
                    //网上找的方法，mac电脑每次询问体验超差
                    for (let i = 0; i < list.length; i++) {
                        setTimeout(()=>{
                            const item = list[i];
                            this.downloadSingleFile(item)
                        },500*i);
                    }
                } else {
                    this.$message.error(res.message);
                }
            },
            downloadSingleFile(item){
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = item.fileUrl;
                a.download = item.fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            },
            //预览
            preview(item) {
                console.log(item.fileUrl);
                if(/\.(mp4?|wmv?|m4v)$/i.test(item.fileUrl)){
                    this.showMovieModal2(item)
                }
                else if (/\.pdf$/i.test(item.fileUrl)) {
                    window.open(item.fileUrl);
                } else if (/\.(docx?|pptx?|xls)$/i.test(item.fileUrl)) {
                    //微软在线预览
                    window.open(`https://view.officeapps.live.com/op/view.aspx?src=${item.fileUrl}`);
                }
            }
        }
    }
</script>

<style scoped lang="less">
    .item:hover {
        background-color: #f0faff;

        .item-top {
            visibility: visible;
        }
    }

    .item .checked {
        background-color: #f0faff;
    }

    .item {
        text-align: center;
        display: inline-block;
        width: 182px;
        /*height: 152px;*/
        margin: 0 0 8px 8px;
        padding: 4px 0;
        border-radius: 8px;
        cursor: pointer;

        &-top {
            visibility: hidden;
            color: #06a7ff;
            font-size: 16px;
            text-align: right;
            min-height: 24px;

            i {
                margin: 0 5px;
            }
        }

        &-name {
            font-size: 12px;
            margin-top: 8px;
            color: #333;
        }

        &-time {
            font-size: 12px;
            color: #afb3bf;
            line-height: 18px;
            margin-top: 2px;
        }
    }

    .item .img-box {
        height: 64px;
    }

    .item img {
        max-width: 64px;
        max-height:100%;
    }

    .text-ellipsis {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    /deep/ .ant-breadcrumb-link {
        color: #1890ff;
    }

    /deep/ .last .ant-breadcrumb-link {
        color: #333333;
    }

    .video-encode {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        background: rgba(200, 200, 200, 0.2);
        color: #999999;
    }

    .file-num {
        color: #afb3bf;
        font-size: 12px;
    }
</style>
